import { Input, InputNumber, Message, Radio } from '@arco-design/web-react';
import { useEffect, useState } from 'react';
import { ValidateRule } from '../../../types';
import DetailItem from '../../../components/detailItem';
import DetailModal from '../../../components/detailModal';
import LoadingMask from '../../../components/loadingMask';
import { getDict, dictDataOptions } from '../../../utils/utils';
import { cloneDeep, validateField } from '../../../utils/utils';
import { apiCardDetailWalletRefundReason, apiUpdateCardDetailWalletRefundReasonDetail } from './api';
import { CardDetailWalletRefundReason } from './types';
interface Props {
  id: string;
  reasonType: string;
  onCancel: (update?: boolean) => void;
}

// 字段验证规则
const rule: ValidateRule = {
  reasonClassify: { required: true, message: '原因分类必填' },
  name: { required: true, message: '退款原因必填' },
  status: { required: true, message: '状态必选' },
  sortNum: { required: true, message: '排序必填' },
};

// 系统开关 状态
const COMMON_ENABLE_STATUS = 'common_enable_status';
export default function CardDetailWalletRefundReasonDetailPage({ id, reasonType, onCancel }: Props) {
  // 页面标题 显示在二级菜单下面
  const pageTitle = (id === 'create' ? '新增' : '修改') + '退款原因';
  // 每次编辑时修改的数据
  const [detailData, setDetailData] = useState<CardDetailWalletRefundReason | null | undefined>({
    status: 'enable',
    reasonType,
  });
  // 数据验证结果
  const [errorData, setErrorData] = useState<{ [x: string]: string }>({});
  const [dictDatas, setDictDatas] = useState<Record<string, any>>({});
    useEffect(() => {
      async function fetchDictData() {
        const data = await getDict(COMMON_ENABLE_STATUS);
        setDictDatas(data);
      }
      fetchDictData();
    }, []); //eslint-disable-line
  

  // --------------额外数据--------------------------------------
  // -----------------------------------------------------------
  // 页面初次渲染时获取数据
  useEffect(() => {
    if (id && id !== 'create') {
      handleRefreshData();
    }
  }, []); //eslint-disable-line

  

  // 当前详情数据请求
  async function handleRefreshData() {
    if (id && id !== 'create') {
      // dispatch(cardDetailWalletRefundReasonDetailRequest({ id, forceRefresh, callback }));
      const res = await apiCardDetailWalletRefundReason(id)
      setDetailData(res?.data?.data);
    }
  }
  // 任意字段修改时存入编辑数据
  function handleChange(key: string, value: any, secondKey?: string, secondValue?: any) {
    let data: any = cloneDeep(detailData);
    data[key] = value;
    if (secondKey) {
      data[secondKey] = secondValue;
    }
    setDetailData(data);
  }
  // 保存
  async function handleSave() {
    let validateRes = validateField(detailData, rule);
    setErrorData(validateRes);
    if (Object.keys(validateRes).length) return;
    LoadingMask.show('正在保存...');
    try {
      let res = await apiUpdateCardDetailWalletRefundReasonDetail(id!, detailData ?? {});
      let data = res.data;
      if (data.code === 200) {
        Message.success({ id: 'save', content: '保存成功' });
        onCancel(true);
        handleRefreshData();
      } else {
        Message.warning({ id: 'save', content: data.msg ?? '保存失败' });
      }
    } catch (e: any) {
      Message.error({ id: 'save', content: e.message ?? '保存失败' });
    } finally {
      LoadingMask.hide();
    }
  }
  //----------------额外操作 / 数据-------------------

  //-------------------------------------------------
  return (
    <DetailModal className="w-600" title={pageTitle} show onConfirm={handleSave} onCancel={() => onCancel()}>
      <DetailItem label="原因分类" required labelSpan={4} outlet={4} error={errorData?.reasonClassify}>
        <Input
          className="m-input"
          value={detailData?.reasonClassify}
          onChange={(v) => handleChange('reasonClassify', v)}
        />
      </DetailItem>
      <DetailItem label="退款原因" required labelSpan={4} outlet={4} error={errorData?.name}>
        <Input className="m-input" value={detailData?.name} onChange={(v) => handleChange('name', v)} />
      </DetailItem>
      <DetailItem label="排序" required labelSpan={4} outlet={4} error={errorData?.sortNum}>
        <InputNumber className="m-input" value={detailData?.sortNum} onChange={(v) => handleChange('sortNum', v)} />
      </DetailItem>
      <DetailItem label="状态" required labelSpan={4} outlet={4} error={errorData?.status}>
        <Radio.Group
          options={dictDataOptions(dictDatas[COMMON_ENABLE_STATUS])}
          value={detailData?.status}
          onChange={(v) => handleChange('status', v)}
        />
      </DetailItem>
      <DetailItem label="备注" labelSpan={4} outlet={4} error={errorData?.remark}>
        <Input.TextArea
          className="m-input"
          maxLength={200}
          showWordLimit
          value={detailData?.remark}
          autoSize={{ minRows: 2 }}
          onChange={(v) => handleChange('remark', v)}
        />
      </DetailItem>
    </DetailModal>
  );
}
